<template>
    <div class="about">
        <!-- 查询 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline" style="display:contents;">
            <el-form-item>
                <el-input v-model="formInline.user" placeholder="歌手或歌曲"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit" plain>查询</el-button>
            </el-form-item>
        </el-form>
        <el-button type="primary" plain @click="dialogSong = true">添加歌曲</el-button>


        <!-- 歌曲表单 -->
        <el-dialog :visible.sync="dialogSong" width="30%" :before-close="handleClose" :close-on-click-modal=false>

            <!-- formNum为true时，展示默认表单  为false展示网易api表单 -->
            <el-form :model="formSong" style="display:contents;" v-if="formNum == true">
                <label>歌曲名</label>
                <el-input v-model="formSong.name" placeholder="歌曲名"></el-input>
                <br /><br />
                <label>歌手名字</label>
                <el-input v-model="formSong.singerName" placeholder="歌手名"></el-input>
                <br /><br />
                <el-form-item label="歌曲文件">
                    <el-upload :limit="1" class="upload-demo" action="/api/saveSong" :before-upload="beforeMusicUpload"
                        :file-list="fileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="歌曲图片">
                    <el-upload :limit="1" class="upload-demo" action="" :before-upload="beforeUpload"
                        accept="image/jpeg,image/png" :file-list="imgList">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <br /><br />
                <el-button type="primary" @click="save" plain>添加</el-button>
                <el-button @click="formNum = false" size="mini">网易音乐Id添加</el-button>
            </el-form>
            <!-- 网易api -->
            <el-form v-else :model="formSong" style="display: contents;">
                <label>歌曲Id</label>
                <el-input v-model="formSong.id" placeholder="输入网易音乐id"></el-input>
                <br /><br />
                <el-button type="primary" @click="getMusicInfo(formSong.id)" plain>获取数据</el-button>
                <br />
                <label>歌曲名</label>
                <el-input v-model="formSong.name" placeholder="歌曲名"></el-input>
                <br /><br />
                <label>歌手名字</label>
                <el-input v-model="formSong.singerName" placeholder="歌手名"></el-input>
                <br /><br />
                <audio v-if="formSong.musicId" controls :src=formSong.musicId></audio>
                <img v-if="formSong.imgId" :src=formSong.imgId width="50px" height="50px">
                <br /><br />
                <el-button type="primary" @click="saveApi" plain>添加</el-button>
                <el-button @click="formNum = true" size="mini">使用默认添加</el-button>
            </el-form>

        </el-dialog>

        <!-- 数据 -->
        <el-table v-loading="loading" :data="tableData" style="width: 60%">
            <el-table-column label="歌曲图片" width="80">
                <template slot-scope="scope">
                    <img v-if="scope.row.imgId && typeof scope.row.imgId === 'string' && scope.row.imgId.startsWith('http')"
                        :src="scope.row.imgId" width="30px" height="30px">
                    <img v-else :src="musicImg + (scope.row.imgId ? scope.row.imgId : '646f20c3af1c000058000a75')"
                        width="30px" height="30px">
                </template>
            </el-table-column>
            <el-table-column prop="name" label="歌名" width="180">
            </el-table-column>
            <el-table-column prop="singer.name" label="歌手" width="180">
            </el-table-column>
            <el-table-column label="操作" width="180">


                <template slot-scope="scope">
                    <el-button type="text" @click="dialogSongOne(scope.row)" size="small" slot="reference">编辑</el-button>
                    &nbsp;
                    <el-popconfirm @confirm="deleteSong(scope.row.id)" title="确定删除吗？">
                        <el-button type="text" size="small" slot="reference">删除</el-button>
                    </el-popconfirm>
                    &nbsp;
                    <el-button v-if="scope.row.root == 1" type="text" @click="updateSong(scope.row.id)" size="small"
                        slot="reference">取消推荐</el-button>
                    <el-button v-else type="text" @click="updateSong(scope.row.id)" size="small"
                        slot="reference">设为推荐</el-button>

                </template>

            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize" :total="total" layout="prev, pager, next, jumper"></el-pagination>

        <!-- 歌曲表单 -->
        <el-dialog title="修改歌曲" :visible.sync="dialogSong1" width="30%">
            <el-form v-model="newSong" style="display: contents;">
                <label>歌曲名</label>
                <el-input v-model="newSong.name" placeholder="歌曲名"></el-input>
                <br /><br />
                <label>歌手名字</label>
                <el-input v-model="newSong.singerName" placeholder="歌手名"></el-input>
                <br /><br /><br /><br />
                <el-button type="primary" @click="updateSong1()" plain>修改</el-button>
            </el-form>
        </el-dialog>


        <!-- 精选列表 -->
        <div style="position: fixed;float: right;top: 100px;right: 50px;height: 400px;overflow: auto;">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>
                        <h3>精选列表</h3>
                    </span>
                </div>
                <el-table :data="songs">
                    <el-table-column prop="name" label="歌名" width="180">
                    </el-table-column>
                    <el-table-column prop="singer.name" label="歌手" width="180">
                    </el-table-column>
                    <el-table-column>
                        <template slot-scope="scope">
                            <el-button type="text" @click="updateSong(scope.row.id)" size="small"
                                slot="reference">取消推荐</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

    </div>
</template>
  
<script>
import infoApi from '@/api/infoApi';
import manageApi from '@/api/manageApi';
import dataApi from '@/api/dataApi';
export default {
    name: 'songView',
    data() {
        return {
            tableData: [],  //表单数据
            formInline: {   //提交的查询表单
                user: '',
            },
            formSong: {     //添加歌曲的表单
                id: null,
                name: "",
                singerName: "",
                musicId: "",
                imgId: ""
            },
            fileList: [],  //音乐文件
            imgList: [], //图片文件
            dialogSong: false,   //添加歌曲的窗口
            dialogSong1: false,  //修改歌曲的窗口
            songs: [],  //推荐歌曲的数组
            newSong: {}, //修改歌曲时的对象，准备传入后端
            musicImg: "/api/getImg/",  //音乐图片的链接
            currentPage: 1, // 当前页码
            pageSize: 10,   // 每页显示的数据量
            total: 0,        // 总数据量
            loading: true,
            formNum: true,
            myImgId: true,
        }
    },
    methods: {
        //获取数据
        getData() {
            this.$emit('childClick1');
            this.loading = true;
            //获得所有歌曲分页
            dataApi.songData({
                params: {
                    page: this.currentPage - 1,
                    size: this.pageSize,
                }
            }).then(response => {
                this.tableData = response.content;
                this.total = response.totalElements;
                this.loading = false;
            }).catch(err => {
                this.$message({
                    message: '错误，请联系管理员',
                    type: 'warning'
                });
                console.log(err);
            })
            //获得所有推荐歌曲
            manageApi.getSongs({
                params: {
                    page: 0,
                    size: 100,
                }
            }).then(response => {
                this.songs = response.data.content
            }).catch(err => {
                this.$message({
                    message: '错误，请联系管理员',
                    type: 'warning'
                });
                console.log(err);
            })
        },
        //查询歌曲或歌手
        onSubmit() {
            this.loading = true;
            manageApi.getSongOrSinger({   //将要查询的字符串作为键值对传入后台
                name: this.formInline.user,
                page: this.currentPage - 1,  //查询的页数
                size: this.pageSize,  //查询的条数
            }).then(response => {
                if (response.data !== "") {  //如果返回的数据不是空的，代表查询成功，获得数据
                    this.tableData = response.data;
                    this.$message({
                        message: '查询成功',
                        type: 'success'
                    });
                } else {
                    this.$message({
                        message: '抱歉，没有添加该歌手或歌曲',
                        type: 'warning'
                    });
                }
                this.loading = false;
            }).catch(err => {
                this.$message({
                    message: '错误，请联系管理员',
                    type: 'warning'
                });
                console.log(err);
            })
        },

        //音乐文件上传前的操作
        beforeMusicUpload(file) {
            // 检查文件类型
            if (file.type !== 'audio/mpeg') {
                this.$message.error('请选择MP3文件');
                return false;
            }
            this.fileList.push(file); // 将选择的文件添加到文件列表中

            const fileName = file.name; // 获取完整的文件名，包含扩展名
            // 获取文件名（不包含扩展名）
            const fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
            const info = fileNameWithoutExtension.split('-');
            this.formSong.singerName = info[0]
            this.formSong.name = info[1]
            // return false; // 阻止默认的文件上传行为
        },
        //图片上传前
        beforeUpload(file) {
            if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
                this.$message.error('请选择图片文件');
                return false;
            }
            this.imgList.push(file); // 将选择的文件添加到文件列表中
            return false; // 阻止默认的文件上传行为
        },

        //添加
        save() {
            const formData = new FormData();  //创建一个FormData对象，可以添加文件
            formData.append('file', this.fileList[0]);  //将音乐文件添加到此对象
            if (!formData.get('file')) {   //如果没有获取到，则提示没有文件
                this.$message({
                    message: '当前没有文件',
                    type: 'warning'
                });
            } else {
                infoApi.saveSongMp3(formData).then(response => {    //发起存储音乐文件的请求
                    //将返回的音乐文件id赋值给musicId
                    this.formSong.musicId = response.data;
                    const imgData = new FormData();   //创建formdata对象，存储图片文件
                    imgData.append('file', this.imgList[0]);
                    if (this.imgList[0] !== undefined) {  //图片文件不为空时
                        manageApi.savaImg(imgData).then(response => {    //存储图片请求
                            this.formSong.imgId = response;
                            manageApi.saveSong(this.formSong).then(response => {  //图片和音乐存储成功后，开始存储音乐信息
                                if (response.data == "") {
                                    this.$message({
                                        message: '歌手名或歌名为空',
                                        type: 'warning'
                                    });
                                } else {
                                    //如果失败，将所有表单数据清空，并关闭窗口
                                    this.dialogSong = false;
                                    this.formSong = {};
                                    this.fileList = [];
                                    this.imgList = [];
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    });
                                    this.getData();
                                    
                                }
                            })
                        }).catch(err => {
                            this.$message({
                                message: '错误，请联系管理员',
                                type: 'warning'
                            });
                            console.log(err);
                        })
                    } else {   //图片为空时直接保存，使用后台默认图片
                        manageApi.saveSong(this.formSong).then(response => {  //图片和音乐存储成功后，开始存储音乐信息
                            if (response.data == "") {
                                this.$message({
                                    message: '歌曲已存在',
                                    type: 'warning'
                                });
                            } else {
                                //如果成功，将所有表单数据清空，并关闭窗口
                                this.dialogSong = false;
                                this.formSong = {};
                                this.fileList = [];
                                this.imgList = [];
                                this.$message({
                                    message: '添加成功',
                                    type: 'success'
                                });
                                this.getData();
                                // location.reload()
                            }

                        }).catch(err => {
                            this.$message({
                                message: '错误，请联系管理员',
                                type: 'warning'
                            });
                            console.log(err);
                        })
                    }

                }).catch(err => {
                    this.$message({
                        message: '文件太大了！',
                        type: 'warning'
                    });
                })
            }
        },
        deleteSong(id) {
            manageApi.deleteSong({ id: id }).then(response => {  //删除歌曲
                if (response.data) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getData();

                } else {
                    this.$message.error('错了哦，这是一条错误消息');
                }

            }).catch(err => {
                this.$message({
                    message: '错误，请联系管理员',
                    type: 'warning'
                });
                console.log(err);
            })
        },
        updateSong(id) {   //更新评论的精选状态
            manageApi.updateSong({ id: id }).then(response => {
                if (response.data) {
                    this.$message({
                        message: '设置成功',
                        type: 'success'
                    });
                    this.getData();

                } else {
                    this.$message.error('错了哦，这是一条错误消息');
                }
            }).catch(err => {
                this.$message({
                    message: '错误，请联系管理员',
                    type: 'warning'
                });
                console.log(err);
            })
        },
        //点击编辑后，将表单数据赋值给newSong对象
        dialogSongOne(data) {
            this.newSong = data;
            this.dialogSong1 = true; 并将窗口展示出来
        },
        //修改歌曲信息
        updateSong1() {
            manageApi.updateSong1(this.newSong).then(response => {  //将新的歌手信息传入后台
                if (response.data) {   //如果返回的true，更新数据
                    this.getData();
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });

                } else {
                    this.$message.error('失败，歌手或歌曲存在重复');
                    this.getData();
                }
            }).catch(err => {
                this.$message({
                    message: '请填写数据',
                    type: 'warning'
                });
                console.log(err);
            })
            this.dialogSong1 = false;
        },
        //关闭窗口时执行
        handleClose() {
            this.formSong = {};
            this.fileList = [];
            this.imgList = [];
            this.dialogSong = false;
        },
        //切换页面时执行
        handlePageChange(page) {
            this.currentPage = page;
            this.getData(); // 切换页码时重新获取数据
        },
        getMusicInfo(id) {
            console.log(id);
            const ids = "[" + id + "]";
            infoApi.getMusicInfo({
                baseURL: '/musicApi/detail',
                params: {
                    ids: ids
                }
            }).then(response => {
                console.log(response.data.songs[0]);
                this.formSong.name = response.data.songs[0].name
                for (let i = 0; i < response.data.songs[0].artists.length; i++) {
                    const element = response.data.songs[0].artists[i];
                    console.log(element);
                    if(i===0){
                        this.formSong.singerName =element.name
                    }else{
                        this.formSong.singerName +="/"+element.name
                    }
                    
                }
                this.formSong.imgId = response.data.songs[0].album.blurPicUrl
                this.formSong.musicId = "http://music.163.com/song/media/outer/url?id=" + id + ".mp3"
                console.log(this.formSong);

            }).catch(err => {
                console.log(err);
                this.$message({
                    message: '请输入正确的id',
                    type: 'warning'
                })
            })
        },
        saveApi() {
            manageApi.saveSong(this.formSong).then(response => {
                if (response.data == "") {
                    this.$message({
                        message: '歌曲已存在，歌手名或歌名为空或',
                        type: 'warning'
                    });
                } else {
                    //如果成功，将所有表单数据清空，并关闭窗口
                    this.dialogSong = false;
                    this.formSong = {};
                    this.fileList = [];
                    this.imgList = [];
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });
                    this.getData();
                }

            }).catch(err => {
                this.$message({
                    message: '请选获取数据',
                    type: 'warning'
                });
                console.log(err);
            })
        }
    },
    mounted() {
        this.getData();
    },
    computed: {
        isPrefixMatched(imgId) {
            return imgId.startsWith('http');
        }
    }

}
</script>